//Validate with regex and output error to defined id
function validateAndOutput(regex, input, errorToWrite, validToWrite, idToWrite) {
	var valid = (regex.test(input));
	validToWrite = '<span class="valid">' + validToWrite + '</span>';
	errorToWrite = '<span class="error">' + errorToWrite + '</span>';
	document.getElementById(idToWrite).innerHTML = valid ? validToWrite : errorToWrite;
	return valid;
}

//Validate with regex and output error to defined id
function validateName() { 
	return validateAndOutput(/^[a-zA-Z ]{5,}$/,document.getElementById('name').value,'ERROR!','OK','nama_info');
}

function validateUname() {
	return validateAndOutput(/^[\w\.]{5,}$/, document.getElementById('uname').value,'ERROR!','OK','uname_info');
}

function validatePw() {
	return validateAndOutput(/^.{6,}$/, document.getElementById('pw').value,'ERROR!','OK','pw_info');
}

function validatePwa() {
	var pw1 = document.getElementById('pw').value;
	var pw2 = document.getElementById('pwa').value;
	if(pw2 != pw1)	document.getElementById('pwa_info').innerHTML = '<span class="error">ERROR</span>';
	else		document.getElementById('pwa_info').innerHTML = '<span class="valid">OK</span>';

        return (pw2 == pw1);
}

function validateEmail() {
	return validateAndOutput(/^\w{5,}@(\w+\.)+\w{2,}$/, document.getElementById('email').value,'ERROR!','OK','email_info');
}

function validateRegistration() {
    var valid =
        validateName() && validateUname() && validatePw() &&
        validatePwa() && validateEmail();
    if(!validateName()) alert("1");
    if(!validateUname()) alert("2");
    if(!validatePw()) alert("3");
    if(!validatePwa()) alert("4");
    if(!validateEmail()) alert("5");

    alert(valid);
    if(!valid) alert("You've entered invalid input in registration form!");

    return valid;
}

function validateLogIn() {
    var r1 = /^[\w\.]{5,}$/;
    var r2 = /^.{6,}$/;
    var valid1 = r1.test(document.getElementById("username_login").value);
    var valid2 = r2.test(document.getElementById("password_login").value);
    var valid = valid1 && valid2;
    if (!valid) alert("You've entered invalid input in sign in form!");

    return valid;
}